package org.jsets.fastboot.frame.controller;

import org.jsets.fastboot.model.BaseResp;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import lombok.extern.slf4j.Slf4j;

/**
 * 异常处理
 *
 * @author wangjie (https://github.com/wj596)
 * @date 2021.07.10 21:57
 * @since 0.1
 */
@Slf4j
// @RestControllerAdvice
public class ExceptionHandlerAdvice {

	@ResponseStatus(HttpStatus.BAD_REQUEST)
	@ExceptionHandler(IllegalArgumentException.class)
	public BaseResp handleIllegalArgumentException(IllegalArgumentException e) {
		log.error(e.getMessage(), e);
		return BaseResp.fail(e.getMessage());
	}

	@ResponseStatus(HttpStatus.BAD_REQUEST)
	@ExceptionHandler(MethodArgumentNotValidException.class)
	public BaseResp handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
		log.error(e.getMessage(), e);
		return BaseResp.fail(e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
	}

	@ResponseStatus(HttpStatus.UNAUTHORIZED)
	@ExceptionHandler(AuthenticationException.class)
	public BaseResp authenticationException(AuthenticationException e) {
		log.error(e.getMessage(), e);
		return BaseResp.fail(e.getMessage());
	}

	@ResponseStatus(HttpStatus.FORBIDDEN)
	@ExceptionHandler(AccessDeniedException.class)
	public BaseResp forbiddenException(AccessDeniedException e) {
		log.error(e.getMessage(), e);
		return BaseResp.fail(e.getMessage());
	}

	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	@ExceptionHandler(value = Exception.class)
	public BaseResp exception(Exception exception) {
		log.error(exception.getMessage(), exception);
		return BaseResp.fail(exception.getMessage());
	}
}